# 用户信息管理的视图文件

from django.db import models

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse

import requests,json,time

# Create your models here.

from myadmin.models import User

def index(request):
    '''浏览信息'''
    try:
        ulist = User.objects.all()
        print(ulist)
        context = {"userlist": ulist}
        return render(request, "myadmin/user/index.html", context)
    except Exception as err:
        return HttpResponse("出错啦："+str(err))


def add(request):
    '''加载添加信息'''
    return render(request, "myadmin/user/useradd.html")

def insert(request):
    '''执行信息添加'''
    try:
        ob = User()
        # 从表单中获取要添加的数据
        ob.username = request.POST['username']
        ob.age = request.POST['age']
        ob.nickname = request.POST['nickname']
        ob.userpwd = request.POST['userpwd']
        ob.save()
        context = {"info": "添加成功！！"}
        return redirect(reverse("myadmin_user_index"))
    except Exception as err:
        return HttpResponse("出错啦："+str(err))


def delete(request,uid=0):
    try:
        ob = User.objects.get(id=uid)
        ob.delete()
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))
    return redirect(reverse("myadmin_user_index"))

def edit(request,uid=0):
    '''浏览信息'''
    try:
        user = User.objects.get(id=uid)
        if user:
            context = {"user": user}
            print(context)
            return render(request, "myadmin/user/useredit.html", context)
        else:
            return HttpResponse("未找到该用户信息！！")
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))

def update(request):
     '''执行编辑信息'''
     try:
         ob = User()
         # 从表单中获取要添加的数据
         ob.id = request.POST['userid']
         ob.username = request.POST['username']
         ob.age = request.POST['age']
         ob.nickname = request.POST['nickname']
         ob.userpwd = request.POST['userpwd']
         ob.save()
         context = {"info": "编辑成功！！"}
         jumpurl = reverse("myadmin_user_index")
         return redirect(jumpurl+"?index=5")
     except Exception as err:
         return HttpResponse("出错啦：" + str(err))
     pass